/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lyh.self.desc.core;

import static java.lang.invoke.MethodType.methodType;

import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileDescriptorSet;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Message;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * google定义自描述文件
 * <pre>
 * https://developers.google.com/protocol-buffers/docs/techniques?hl=zh-CN#self-description
 * </pre>
 */
@SuppressWarnings("unchecked")
public class ProtoDescParserFactory {

    //class name in proto file
    private static Map<String, MethodHandle> PARSE_METHODS_PROTO           = new HashMap<>();
    // class name in java file
    private static Map<String, MethodHandle> PARSE_METHODS_JAVA            = new HashMap<>();
    //class name in java file
    private static Map<String, MethodHandle> DEFAULT_INSTANCE_METHODS_JAVA = new HashMap<>();
    private static Map<String, Message>      DEFAULT_MESSAGE_INSTANCE      = new ConcurrentHashMap<>();

    static {
        try {
            final FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(ProtoDescFile.getProtoDescFile());
            final List<FileDescriptor> resolveFDs = new ArrayList<>();
            for (final FileDescriptorProto fdp : descriptorSet.getFileList()) {
                final FileDescriptor[] dependencies = new FileDescriptor[resolveFDs.size()];
                resolveFDs.toArray(dependencies);
                final FileDescriptor fd = FileDescriptor.buildFrom(fdp, dependencies);
                resolveFDs.add(fd);
                for (final Descriptor descriptor : fd.getMessageTypes()) {
                    final String className = getClassName(fdp, fd, descriptor);
                    final Class<?> clazz = Class.forName(className);
                    final MethodHandle parseFromHandler = MethodHandles.lookup().findStatic(clazz, "parseFrom",
                        methodType(clazz, byte[].class));
                    final MethodHandle getInstanceHandler = MethodHandles.lookup().findStatic(clazz,
                        "getDefaultInstance", methodType(clazz));
                    System.out.println(String.format("注册MessageProtoName：%s", descriptor.getFullName()));
                    PARSE_METHODS_PROTO.put(descriptor.getFullName(), parseFromHandler);
                    System.out.println(String.format("注册MessageJavaName：%s", className));
                    PARSE_METHODS_JAVA.put(className, parseFromHandler);
                    System.out.println(String.format("注册getDefaultInstance：%s", className));
                    DEFAULT_INSTANCE_METHODS_JAVA.put(className, getInstanceHandler);
                    registerProtobufSerializer(className, (Message) getInstanceHandler.invoke());
                }
            }
        } catch (final Throwable t) {
            t.printStackTrace(); // NOPMD
        }
    }

    private static String getClassName(FileDescriptorProto fdp, FileDescriptor fd, Descriptor descriptor) {
        final String className;
        String packageName = fd.getOptions().getJavaPackage();
        if (fdp.getOptions().hasJavaOuterClassname()) {
            className = packageName + "." + fdp.getOptions().getJavaOuterClassname() + "$" + descriptor.getName();
        } else if (fdp.getOptions().hasJavaMultipleFiles()) {
            className = packageName + "." + descriptor.getName();
        } else {
            String protoFileName = fdp.getName().substring(0, fdp.getName().length() - 6);
            char[] chats = protoFileName.toCharArray();
            if (Character.isLowerCase(chats[0])) {
                chats[0] = Character.toUpperCase(chats[0]);
            }//TODO 这里只是简单处理了首字母大写转化处理
            className = packageName + "." + new String(chats) + "$" + descriptor.getName();
        }
        return className;
    }

    private static void registerProtobufSerializer(String className, Message message) {
        DEFAULT_MESSAGE_INSTANCE.putIfAbsent(className, message);
    }

    public static void load() {
        if (PARSE_METHODS_JAVA.isEmpty() || PARSE_METHODS_PROTO.isEmpty() || DEFAULT_INSTANCE_METHODS_JAVA.isEmpty()) {
            throw new IllegalStateException("Parse protocol file failed.");
        }
    }

    public static <T extends Message> T getDefaultInstance(final String className) {
        final MethodHandle handle = DEFAULT_INSTANCE_METHODS_JAVA.get(className);
        if (handle == null) {
            throw new MessageClassNotFoundException(className + " not found");
        }
        try {
            return (T) handle.invoke();
        } catch (Throwable t) {
            throw new SerializationException("getDefaultInstance(" + className + ") ERROR", t);
        }
    }

    public static <T extends Message> T newMessageByJavaClassName(final String className, final byte[] bs) {
        final MethodHandle handle = PARSE_METHODS_JAVA.get(className);
        if (handle == null) {
            throw new MessageClassNotFoundException(className + " not found");
        }
        try {
            return (T) handle.invoke(bs);
        } catch (Throwable t) {
            throw new SerializationException("newMessageByJavaClassName(className:" + className + ") ERROR", t);
        }
    }

    public static <T extends Message> T newMessageByProtoClassName(final String className, final byte[] bs) {
        final MethodHandle handle = PARSE_METHODS_PROTO.get(className);
        if (handle == null) {
            throw new MessageClassNotFoundException(className + " not found");
        }
        try {
            return (T) handle.invoke(bs);
        } catch (Throwable t) {
            throw new SerializationException("newMessageByProtoClassName(protoName:" + className + ")", t);
        }
    }
}
